package com.ruoyi.ldzlsc.service.Impl;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.ldzlsc.domain.vo.ScBomDetailVo;
import com.ruoyi.ldzlsc.domain.vo.ScBomVo;
import com.ruoyi.ldzlsc.domain.vo.ScProductionPlanDetailVo;
import com.ruoyi.ldzlsc.mapper.ScBomMapper;
import com.ruoyi.ldzlsc.mapper.ScProductionPlanMapper;
import com.ruoyi.ldzlsc.service.IScBomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * BOM服务实现类
 *
 * @author ruoyi
 * @date 2025-07-30
 */
@Service
public class ScBomServiceImpl implements IScBomService {

    @Autowired
    private ScBomMapper scBomMapper;

    @Autowired
    private ScProductionPlanMapper scProductionPlanMapper;

    /**
     * 根据生产计划编号查询BOM信息
     * 
     * @param planCode 生产计划编号
     * @return BOM信息
     */
    @Override
    public ScBomVo selectBomByPlanCode(String planCode) {
        if (planCode == null || planCode.trim().isEmpty()) {
            throw new ServiceException("生产计划编号不能为空");
        }

        // 1. 根据计划编号查询计划明细，获取产品ID
        List<ScProductionPlanDetailVo> planDetails = scProductionPlanMapper.selectPlanDetailListByPlanCode(planCode);
        if (planDetails == null || planDetails.isEmpty()) {
            throw new ServiceException("未找到生产计划明细: " + planCode);
        }

        // 使用第一条明细的产品ID
        Long productId = planDetails.get(0).getProductId();
        if (productId == null) {
            throw new ServiceException("生产计划明细中缺少产品ID");
        }

        // 2. 根据产品ID查询BOM信息
        return selectBomByProductId(productId);
    }

    /**
     * 根据产品ID查询BOM信息
     * 
     * @param productId 产品ID
     * @return BOM信息
     */
    @Override
    public ScBomVo selectBomByProductId(Long productId) {
        if (productId == null) {
            throw new ServiceException("产品ID不能为空");
        }

        // 查询BOM基本信息
        ScBomVo bomVo = scBomMapper.selectBomByProductId(productId);
        if (bomVo == null) {
            throw new ServiceException("未找到产品的BOM信息: " + productId);
        }

        // 查询BOM明细列表
        List<ScBomDetailVo> bomDetails = scBomMapper.selectBomDetailListByBomId(bomVo.getBomId());
        bomVo.setDetails(bomDetails);

        return bomVo;
    }
}
